package com.longyiqun.apitest;

import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import org.apache.commons.codec.Charsets;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * program: ApiTest
 * package: com.longyiqun.apitest
 * author: 龙轶群
 * create: 2018-04-02 11:11
 **/

public class BussinessUtil {

    // IMPORTANT KEY
    public static final String PRIMARYKEY = "befd551c993d31a10f1bbfed0ef6de7e";

    // TO MD5
    public static String converToMD5(String md5)
    {
        @SuppressWarnings("deprecation")
        HashCode hashCode = Hashing.md5().hashString(md5, Charsets.UTF_8);
        String str = hashCode.toString();
        return str;
    }

    public static boolean validateSignature(Map<String, String> params, String signature) {
        if (BussinessUtil.isValid(signature)) {
            String validateSignature = BussinessUtil.getRequestSignature(params);
            if (BussinessUtil.isValid(validateSignature) && validateSignature.equals(signature)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取签名
     */
    public static String getRequestSignature(Map<String, String> params) {
        StringBuilder signature = new StringBuilder();
        String[] arr = new String[params.size() + 1];

        arr[0] = PRIMARYKEY;
        int i = 0;
        // iterating over values only
        for (Object value : params.values()) {
            arr[i + 1] = (String) (value != null ? value : "");
            i++;
        }

        Arrays.sort(arr);

        for (String string : arr) {
            signature.append(string);
        }

        return sha1UTF8(signature.toString());
    }

    // 将字符串SHA
    public static String sha1UTF8(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("utf-8"), 0, text.length());
            byte[] sha1hash = md.digest();
            return convertToHex(sha1hash);
        } catch (Exception e) {
            return "";
        }
    }

    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    /**
     * 将对象转为json
     */
    public static boolean isValid(String str) {
        boolean isValid = false;
        if (str != null && !"".equals(str.trim())) {
            isValid = true;
        }
        return isValid;
    }

    /**
     * 从短信字符窜提取验证码
     *
     * @param body      短信内容
     * @param YZMLENGTH 验证码的长度 一般6位或者4位
     * @return 接取出来的验证码
     */
    public static String getyzm(String body, int YZMLENGTH) {
        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
        Pattern p = Pattern.compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");
        Matcher m = p.matcher(body);
        if (m.find()) {
            return m.group(0);
        }
        return null;
    }
}